local skynet = require "skynet"
local socket = require "skynet.socket"

--param:fd-与客户端连接的socketfd的id, addr-客户端IP:port
function ClientConnect(fd, addr)
    skynet.error("socketfdID is "..fd.." connected addr="..addr)
    socket.start(fd)  --再次调用start, 开始接收来自客户端的数据, 这次调用没有输入connect参数, skynet内部对此作了区分处理
    while true do
        local readdata = socket.read(fd)  --socket.read是个阻塞函数
        if readdata then
            skynet.error("socketfdID "..fd.." recv: "..readdata)
            socket.write(fd, readdata)  --将接收到的数据回传
        else
            skynet.error("socketfdID "..fd.." close")
            socket.close(fd)
        end
    end
end

skynet.start(function()
    skynet.error("Echo Server start")
    local listen_socket_id = socket.listen("0.0.0.0", 8888) --监听8888端口
    skynet.error("Echo Server listen_socket_id is " .. listen_socket_id)
    socket.start(listen_socket_id, ClientConnect) --有新的客户端连接时，调用ClientConnect所代表的local函数
end)

--客户端发起连接: telnet 127.0.0.1 8888